Autonomous driving - Car detection

Welcome to your week 3 programming assignment. You will learn about object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: Redmon et al., 2016 and Redmon and Farhadi, 2016.

You will learn to:

Updates

If you were working on the notebook before this update...

List of updates

Import libraries

Run the following cell to load the packages and dependencies that you will find useful as you build the object detector!

Important Note: As you can see, we import Keras's backend as K. This means that to use a Keras function in this notebook, you will need to write: K.function(...).

1 - Problem Statement

You are working on a self-driving car. As a critical component of this project, you'd like to first build a car detection system. To collect data, you've mounted a camera to the hood (meaning the front) of the car, which takes pictures of the road ahead every few seconds while you drive around.

Pictures taken from a car-mounted camera while driving around Silicon Valley.
We thank [drive.ai](htps://www.drive.ai/) for providing this dataset.

You've gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like.

**Figure 1** : **Definition of a box**

If you have 80 classes that you want the object detector to recognize, you can represent the class label $c$ either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) one component of which is 1 and the rest of which are 0. The video lectures had used the latter representation; in this notebook, we will use both representations, depending on which is more convenient for a particular step.

In this exercise, you will learn how "You Only Look Once" (YOLO) performs object detection, and then apply it to car detection. Because the YOLO model is very computationally expensive to train, we will load pre-trained weights for you to use.

2 - YOLO

"You Only Look Once" (YOLO) is a popular algorithm because it achieves high accuracy while also being able to run in real-time. This algorithm "only looks once" at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.

2.1 - Model details

Inputs and outputs

Anchor Boxes

Encoding

Let's look in greater detail at what this encoding represents.

**Figure 2** : **Encoding architecture for YOLO**

If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object.

Since we are using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.

For simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425).

**Figure 3** : **Flattening the last two last dimensions**

Class score

Now, for each box (of each cell) we will compute the following element-wise product and extract a probability that the box contains a certain class.
The class score is $score_{c,i} = p_{c} \times c_{i}$: the probability that there is an object $p_{c}$ times the probability that the object is a certain class $c_{i}$.

**Figure 4** : **Find the class detected by each box**
Example of figure 4

Visualizing classes

Here's one way to visualize what YOLO is predicting on an image:

Doing this results in this picture:

**Figure 5** : Each one of the 19x19 grid cells is colored according to which class has the largest predicted probability in that cell.

Note that this visualization isn't a core part of the YOLO algorithm itself for making predictions; it's just a nice way of visualizing an intermediate result of the algorithm.

Visualizing bounding boxes

Another way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this:

**Figure 6** : Each cell gives you 5 boxes. In total, the model predicts: 19x19x5 = 1805 boxes just by looking once at the image (one forward pass through the network)! Different colors denote different classes.

Non-Max suppression

In the figure above, we plotted only boxes for which the model had assigned a high probability, but this is still too many boxes. You'd like to reduce the algorithm's output to a much smaller number of detected objects.

To do so, you'll use non-max suppression. Specifically, you'll carry out these steps:

2.2 - Filtering with a threshold on class scores

You are going to first apply a filter by thresholding. You would like to get rid of any box for which the class "score" is less than a chosen threshold.

The model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It is convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables:

Exercise: Implement yolo_filter_boxes().

  1. Compute box scores by doing the elementwise product as described in Figure 4 ($p \times c$).
    The following code may help you choose the right operator:

    a = np.random.randn(19*19, 5, 1)
    b = np.random.randn(19*19, 5, 80)
    c = a * b # shape of c will be (19*19, 5, 80)
    

    This is an example of broadcasting (multiplying vectors of different sizes).

  2. For each box, find:

    • the index of the class with the maximum box score
    • the corresponding box score

      Useful references

      Additional Hints

      • For the axis parameter of argmax and max, if you want to select the last axis, one way to do so is to set axis=-1. This is similar to Python array indexing, where you can select the last position of an array using arrayname[-1].
      • Applying max normally collapses the axis for which the maximum is applied. keepdims=False is the default option, and allows that dimension to be removed. We don't need to keep the last dimension after applying the maximum here.
      • Even though the documentation shows keras.backend.argmax, use keras.argmax. Similarly, use keras.max.
  1. Create a mask by using a threshold. As a reminder: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep.

  2. Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep.

    Useful reference:

    Additional Hints:

    • For the tf.boolean_mask, we can keep the default axis=None.

Reminder: to call a Keras function, you should use K.function(...).

Expected Output:

**scores[2]** 10.7506
**boxes[2]** [ 8.42653275 3.27136683 -0.5313437 -4.94137383]
**classes[2]** 7
**scores.shape** (?,)
**boxes.shape** (?, 4)
**classes.shape** (?,)

Note In the test for yolo_filter_boxes, we're using random numbers to test the function. In real data, the box_class_probs would contain non-zero values between 0 and 1 for the probabilities. The box coordinates in boxes would also be chosen so that lengths and heights are non-negative.

2.3 - Non-max suppression

Even after filtering by thresholding over the class scores, you still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS).

**Figure 7** : In this example, the model has predicted 3 cars, but it's actually 3 predictions of the same car. Running non-max suppression (NMS) will select only the most accurate (highest probability) of the 3 boxes.

Non-max suppression uses the very important function called "Intersection over Union", or IoU.

**Figure 8** : Definition of "Intersection over Union".

Exercise: Implement iou(). Some hints:

Additional Hints

Expected Output:

iou for intersecting boxes = 0.14285714285714285
iou for non-intersecting boxes = 0.0
iou for boxes that only touch at vertices = 0.0
iou for boxes that only touch at edges = 0.0

YOLO non-max suppression

You are now ready to implement non-max suppression. The key steps are:

  1. Select the box that has the highest score.
  2. Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold).
  3. Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.

This will remove all boxes that have a large overlap with the selected boxes. Only the "best" boxes remain.

Exercise: Implement yolo_non_max_suppression() using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your iou() implementation):

Reference documentation

Expected Output:

**scores[2]** 6.9384
**boxes[2]** [-5.299932 3.13798141 4.45036697 0.95942086]
**classes[2]** -2.24527
**scores.shape** (10,)
**boxes.shape** (10, 4)
**classes.shape** (10,)

2.4 Wrapping up the filtering

It's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented.

Exercise: Implement yolo_eval() which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which we have provided):

boxes = yolo_boxes_to_corners(box_xy, box_wh)

which converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of yolo_filter_boxes

boxes = scale_boxes(boxes, image_shape)

YOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image--for example, the car detection dataset had 720x1280 images--this step rescales the boxes so that they can be plotted on top of the original 720x1280 image.

Don't worry about these two functions; we'll show you where they need to be called.

Expected Output:

**scores[2]** 138.791
**boxes[2]** [ 1292.32971191 -278.52166748 3876.98925781 -835.56494141]
**classes[2]** 54
**scores.shape** (10,)
**boxes.shape** (10, 4)
**classes.shape** (10,)

Summary for YOLO:

3 - Test YOLO pre-trained model on images

In this part, you are going to use a pre-trained model and test it on the car detection dataset. We'll need a session to execute the computation graph and evaluate the tensors.

3.1 - Defining classes, anchors and image shape.

3.2 - Loading a pre-trained model

Run the cell below to load the model from this file.

This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains.

Note: On some computers, you may see a warning message from Keras. Don't worry about it if you do--it is fine.

Reminder: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2).

3.3 - Convert output of the model to usable bounding box tensors

The output of yolo_model is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following cell does that for you.

If you are curious about how yolo_head is implemented, you can find the function definition in the file 'keras_yolo.py'. The file is located in your workspace in this path 'yad2k/models/keras_yolo.py'.

You added yolo_outputs to your graph. This set of 4 tensors is ready to be used as input by your yolo_eval function.

3.4 - Filtering boxes

yolo_outputs gave you all the predicted boxes of yolo_model in the correct format. You're now ready to perform filtering and select only the best boxes. Let's now call yolo_eval, which you had previously implemented, to do this.

3.5 - Run the graph on an image

Let the fun begin. You have created a graph that can be summarized as follows:

  1. yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output
  2. yolo_model.output is processed by yolo_head. It gives you yolo_outputs
  3. yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes

Exercise: Implement predict() which runs the graph to test YOLO on an image. You will need to run a TensorFlow session, to have it compute scores, boxes, classes.

The code below also uses the following function:

image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608))

which outputs:

Important note: when a model uses BatchNorm (as is the case in YOLO), you will need to pass an additional placeholder in the feed_dict {K.learning_phase(): 0}.

Hint: Using the TensorFlow Session object

Run the following cell on the "test.jpg" image to verify that your function is correct.

Expected Output:

**Found 7 boxes for test.jpg**
**car** 0.60 (925, 285) (1045, 374)
**car** 0.66 (706, 279) (786, 350)
**bus** 0.67 (5, 266) (220, 407)
**car** 0.70 (947, 324) (1280, 705)
**car** 0.74 (159, 303) (346, 440)
**car** 0.80 (761, 282) (942, 412)
**car** 0.89 (367, 300) (745, 648)

The model you've just run is actually able to detect 80 different classes listed in "coco_classes.txt". To test the model on your own images:

1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub.
2. Add your image to this Jupyter Notebook's directory, in the "images" folder
3. Write your image's name in the cell above code
4. Run the code and see the output of the algorithm!

If you were to run your session in a for loop over all your images. Here's what you would get:

Predictions of the YOLO model on pictures taken from a camera while driving around the Silicon Valley
Thanks [drive.ai](https://www.drive.ai/) for providing this dataset!

What you should remember:

  • YOLO is a state-of-the-art object detection model that is fast and accurate
  • It runs an input image through a CNN which outputs a 19x19x5x85 dimensional volume.
  • The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.
  • You filter through all the boxes using non-max suppression. Specifically:
    • Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes
    • Intersection over Union (IoU) thresholding to eliminate overlapping boxes
  • Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise.